import Vue from 'vue'
const debounce = (func, time, ctx, immediate = true) => {
  let timeout
  return function (...params) {
    if (timeout) clearTimeout(timeout)
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, time)
      if (callNow) func.apply(ctx, params)
    } else {
      timeout = setTimeout(function () {
        func.apply(ctx, params)
      }, time)
    }
  }
}

Vue.component('Debounce', {
  abstract: true,
  props: ['time', 'events', 'immediate'],
  created () {
    this.eventKeys = this.events && this.events.split(',')
    this.originMap = {}
    this.debouncedMap = {}
  },
  render () {
    const vnode = this.$slots.default[0]
    // 如果默认没有传 events，则对所有绑定事件加上防抖
    if (!this.eventKeys) {
      this.eventKeys = Object.keys(vnode.data.on)
    }
    this.eventKeys.forEach((key) => {
      const target = vnode.data.on[key]
      if (target === this.originMap[key] && this.debouncedMap[key]) {
        vnode.data.on[key] = this.debouncedMap[key]
      } else if (target) {
        this.originMap[key] = target
        this.debouncedMap[key] = debounce(target, this.time, vnode, this.immediate)
        vnode.data.on[key] = this.debouncedMap[key]
      }
    })
    return vnode
  }
})
